package com.c.ctgproject.ui.collect

import android.content.Intent
import android.view.View
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.c.ctgproject.adapter.guang.CarWeighingAdapter
import com.c.ctgproject.base.BaseActivityV2
import com.c.ctgproject.databinding.ActivityCarListBinding
import com.c.ctgproject.entity.guang.CarListEntity
import com.c.ctgproject.event.CarListBatteryOilEvent
import com.c.ctgproject.event.PositionEvent
import com.c.ctgproject.http.ApiMethods
import com.c.ctgproject.http.MyObserverHandlerLoading
import com.c.ctgproject.utils.*
import com.c.ctgproject.wiget.dialog.CommonAlertDialog
import com.google.gson.Gson
import io.reactivex.Observable
import okhttp3.ResponseBody
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.startActivityForResult

/**
 *作者:LiBW
 *创建日期: 2021/9/8
 *描述:车辆列表 页面(通用)
 */
class CarListActivity : BaseActivityV2(true), CarWeighingAdapter.CarWeighingAdapterListener ,CarWeighingAdapter.CarWeighingAdapterCheckedLister{
    private val mBinding by lazy { ActivityCarListBinding.inflate(layoutInflater) }

    override fun getLayout() = mBinding.root
    private var searchMine = false
    private var page = 1
    private var search: String = ""
    private var mList = ArrayList<CarListEntity.DataBean.ListBean>()
    private val mName by lazy { intent.getStringExtra(MyConstants.TITLE_NAME) }

    private val carIdList=ArrayList<Int>()
    private val mViewModel:CarListViewModel by lazy { ViewModelProvider(this)[CarListViewModel::class.java] }
    private val mAdapter by lazy { CarWeighingAdapter(this, mList, mName, this,this,mViewModel) }
    @Subscribe
    fun event(type: PositionEvent) {
        MyLog.d("入库:${type.position}")
        type.position?.let {
            if (it == -1) return
            //mList.removeAt(it)
            //carIdList.remove(mList[type.position].carId)
            initData()
            if(carIdList.isEmpty()){
                mBinding.mConfirmBTN.text="通过"
                mBinding.mRejectBTN.text="驳回"
            }else{
                mBinding.mConfirmBTN.text="通过（${carIdList.size}）"
                mBinding.mRejectBTN.text="驳回（${carIdList.size}）"
            }
            //mAdapter.notifyItemRemoved(it)
        }

    }

    override fun onRestart() {
        super.onRestart()
//        page = 1
//        getData()
    }

    @Subscribe
    fun event(type: CarListBatteryOilEvent) {
        val position = type.position
        when {
            //全部处理完毕
            position != -1 && type.oil && type.battery -> {
                mList.removeAt(position)
                mAdapter.notifyItemRemoved(position)
            }
            //处理完电池了
            position != -1 && !type.oil && type.battery -> {
                if (mList[position].oilWaterDrainage==1){
                    //如果之前油水已经处理完了直接移除
                    mList.removeAt(position)
                    mAdapter.notifyItemRemoved(position)
                }else{
                    mList[position].batteryDisassemble=1
                    mAdapter.notifyItemChanged(position)
                }
            }
            //处理完油水
            position != -1 && type.oil && !type.battery -> {
                if (mList[position].batteryDisassemble==1){
                    //如果之前电池已经处理完了直接移除
                    mList.removeAt(position)
                    mAdapter.notifyItemRemoved(position)
                    mAdapter.notifyDataSetChanged()
                }else{
                    mList[position].oilWaterDrainage=1
                    mAdapter.notifyItemChanged(position)
                }
            }
        }

        type.position?.let {
            if (it == -1) return

        }
    }

    override fun event() {
        getData()
        when (mName) {
            "登记入库" -> {
                mBinding.mTitleBar.setTitle("待入库车辆")
                val l = mBinding.mTabLayout.newTab()
                l.text = "未入库"
                mBinding.mTabLayout.addTab(l)
                val r = mBinding.mTabLayout.newTab()
                r.text = "我的"
                mBinding.mTabLayout.addTab(r)
            }
            "车辆过磅" -> {
                mBinding.mBottomRL.visibility=View.VISIBLE
                mBinding.mTitleBar.setTitle("待过磅车辆")
                val l = mBinding.mTabLayout.newTab()
                l.text = "未过磅"
                mBinding.mTabLayout.addTab(l)
                val r = mBinding.mTabLayout.newTab()
                r.text = "我的"
                mBinding.mTabLayout.addTab(r)
            }
            "车辆初检" -> {
                mBinding.mBottomRL.visibility=View.VISIBLE
                mBinding.mRejectBTN.visibility=View.VISIBLE
                mBinding.mConfirmBTN.text="通过"
                val l = mBinding.mTabLayout.newTab()
                l.text = "未初检"
                mBinding.mTabLayout.addTab(l)
                val r = mBinding.mTabLayout.newTab()
                r.text = "我的"
                mBinding.mTabLayout.addTab(r)
                mBinding.mTitleBar.setTitle("待初检车辆")
            }
            "车辆预处理" -> {
                val l = mBinding.mTabLayout.newTab()
                l.text = "未处理"
                mBinding.mTabLayout.addTab(l)
                val r = mBinding.mTabLayout.newTab()
                r.text = "我的"
                mBinding.mTabLayout.addTab(r)
                mBinding.mTitleBar.setTitle("待预处理车辆")
            }
        }
        mBinding.mCarRV.adapter = mAdapter
        mBinding.mCarRV.layoutManager = LinearLayoutManager(this)
        mViewModel.searchMine.observe(this, Observer {
           if (it){
               mBinding.mBottomRL.visibility=View.GONE
           }else{
               if(mName!="登记入库"){
                   mBinding.mBottomRL.visibility=View.VISIBLE
               }
           }
        })
    }


    override fun click() {
        mBinding.mConfirmBTN.setOnClickListener {
            when(mName){
                "车辆过磅"->{
                    if (carIdList.isEmpty()){
                        showToast("还未选择待过磅设备")
                    }else{
                        startActivityForResult<CarWeighingChildActivity>(
                            1001,
                            MyConstants.CAR_ID_LIST to Gson().toJson(carIdList)
                        )
                    }
                }
                "车辆初检"->{
                    if (carIdList.isEmpty()){
                        showToast("还未选择未初检设备")
                    }else{
                       submit(true)
                    }
                }
            }

        }
        mBinding.mRejectBTN.setOnClickListener {
            if (carIdList.isEmpty()){
                showToast("还未选择驳回设备")
            }else{
                submit(false)
            }
        }
        mBinding.mTabLayout.handlerSelectReturnText {
            when (it) {
                "未入库", "未过磅", "未初检", "未处理" -> {
                    searchMine = false
                    mViewModel.changeSearchMine(false)
                    page = 1
                    getData()
                }
                "我的" -> {
                    searchMine = true
                    mViewModel.changeSearchMine(true)
                    page = 1
                    getData()
                }
            }
        }
        mBinding.mSearchET.handlerText {
            //加个限制，防止黑屏
            if(mBinding.mSearchET.isFocusableInTouchMode)
            {
                if (it.isEmpty() || it == "") {
                    search = ""
                    page = 1
                    getData()
                }
            }

        }
        mBinding.mSearchTV.setOnClickListener {
            search = mBinding.mSearchET.text.handlerNull()
            page = 1
            getData()
        }
        mBinding.mRefresh.setOnLoadMoreListener {
            page++
            getData()
        }

        mBinding.mRefresh.setOnRefreshListener {
            page = 1
            getData()
        }

    }




    private fun getData() {
        carIdList.clear()
        if (searchMine) {
            //流程类型 1-预录入 2-登记入库 3-过磅 4-初检 5-预处理 6-新建拆解 7-完成拆解 8-毁型拍照
            val statueType = when (mName) {
                "登记入库" -> {
                    2
                }
                "车辆过磅" -> {
                    3
                }
                "车辆初检" -> {
                    4
                }
                "车辆预处理" -> {
                    5
                }
                else -> {
                    -1
                }
            }
            ApiMethods.apiSubscribe(ApiMethods.retrofit.myHandlerCar(search, statueType, page), MyObserverHandlerLoading(this, loading, mBinding.mRefresh) {
                MyLog.d("我的车辆列表:$it")
                if (page == 1) mList.clear()
                val data = getGson().fromJson(it, CarListEntity::class.java).data
                data?.list?.let { list ->
                    mList.addAll(list)
                    mAdapter.notifyDataSetChanged()
                    mBinding.mCarRV.handlerPosition(page)
                }
            })
        } else {
            when (mName) {
                "登记入库" -> {
                    getDataChild(ApiMethods.retrofit.waitIn(search, page))
                }
                "车辆过磅" -> {
                    getDataChild(ApiMethods.retrofit.waitGetWidget(search, page))
                }
                "车辆初检" -> {
                    getDataChild(ApiMethods.retrofit.waitFirstCheck(search, page))
                }
                "车辆预处理" -> {
                    getDataChild(ApiMethods.retrofit.waitPerHandler(search, page))
                }

                else -> {

                }
            }
        }
    }

    private fun getDataChild(get: Observable<ResponseBody>) {
        ApiMethods.apiSubscribe(get, MyObserverHandlerLoading(this, loading, mBinding.mRefresh) {
            MyLog.d("车辆列表:$it")
            if (page == 1) mList.clear()
            carIdList.clear()
            when(mName){
                "车辆过磅"->{
                    if(carIdList.isEmpty()){
                        mBinding.mConfirmBTN.text="过磅"
                    }else{
                        mBinding.mConfirmBTN.text="过磅（${carIdList.size}）"
                    }
                }
            }
            val data = getGson().fromJson(it, CarListEntity::class.java).data
            data?.list?.let { list ->
                mList.addAll(list)
                mAdapter.notifyDataSetChanged()
                mBinding.mCarRV.handlerPosition(page)
            }
        })
    }

    //排油水
    override fun onWaterClick(position: Int) {
        CommonAlertDialog(this, "确认将排油水设置为已完成么") {
            ApiMethods.apiSubscribe(ApiMethods.retrofit.handlerWater(mList[position].carId), MyObserverHandlerLoading(this, loading) {
                MyLog.d("排油水回调:$it")
                showToast("提交成功")
                val event=CarListBatteryOilEvent()
                event.position=position
                event.oil=true
                EventBus.getDefault().post(event)
            })
        }.show()


//        commonDialog("确认将排油水设置为已完成么") {
//            ApiMethods.apiSubscribe(ApiMethods.retrofit.handlerWater(mList[position].carId), MyObserverHandlerLoading(this, loading) {
//                MyLog.d("排油水回调:$it")
//                showToast("提交成功")
//                mList[position].oilWaterDrainage = 1
//                mAdapter.notifyItemChanged(position)
//            })
//        }
    }

    override fun onWeightChecked(position: Int, checked: Boolean) {
        if(checked){
            carIdList.add(mList[position].carId)
        }else{
            carIdList.remove(mList[position].carId)
        }
        when(mName){
            "车辆过磅"->{
                if(carIdList.isEmpty()){
                    mBinding.mConfirmBTN.text="过磅"
                }else{
                    mBinding.mConfirmBTN.text="过磅（${carIdList.size}）"
                }
            }
            "车辆初检"->{
                if(carIdList.isEmpty()){
                    mBinding.mConfirmBTN.text="通过"
                    mBinding.mRejectBTN.text="驳回"
                }else{
                    mBinding.mConfirmBTN.text="通过（${carIdList.size}）"
                    mBinding.mRejectBTN.text="驳回（${carIdList.size}）"
                }
            }
        }

    }



    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when(requestCode){
            1001->{
                if(resultCode==1){
                    //initData()//提交成功后重新获取数据刷新界面
                    //mList.removeAt(it)
                    for(i in 0 until mList.size-1){
                        if(carIdList.contains(mList[i].carId)){
                            carIdList.remove(mList[i].carId)
                            mList.removeAt(i)
                        }
                    }
                    mAdapter.notifyDataSetChanged()
                    if(carIdList.isEmpty()){
                        mBinding.mConfirmBTN.text="过磅"
                    }else{
                        mBinding.mConfirmBTN.text="过磅（${carIdList.size}）"
                    }
                    //carIdList.remove(mList[type.position].carId)
                }
            }
        }
    }
    private fun initData(){
        mList.clear()
        page=1
        getData()
    }
    private fun submit(success: Boolean) {
        val map = HashMap<String, Any>()
        map["carIdList"] = carIdList
        map["result"] = if (success) 1 else 2
        //val remark = mBinding.mRemarkET.text.handlerNull()
       // if (remark.isNotEmpty()) map["remark"] = remark
        ApiMethods.apiSubscribe(ApiMethods.retrofit.firstCheck(handlerBody(map)), MyObserverHandlerLoading(this, loading) {
            MyLog.d("初检回调:$it")
            showToast("提交成功")
            carIdList.clear()
            if(carIdList.isEmpty()){
                mBinding.mConfirmBTN.text="通过"
                mBinding.mRejectBTN.text="驳回"
            }else{
                mBinding.mConfirmBTN.text="通过（${carIdList.size}）"
                mBinding.mRejectBTN.text="驳回（${carIdList.size}）"
            }
            //EventBus.getDefault().post(PositionEvent(mListPosition))
            initData()
        })
    }
}